<?php

/**
 *  产品筛选器
 */

namespace app\api\service;

use app\api\model\ProductBrand;
use app\api\model\ProductCurrency;
use app\api\model\Warehouse;
use app\facade\Basic;
use think\facade\Db;
use app\admin\model\Algorithm;
use app\api\logic\CacheLogic;

class ProductFilter
{

    protected $refresh = false;

    public function __construct()
    {
        $this->refresh = env('ENV_REFRESH_CACHE', false);
    }

    /**
     *  框架品牌
     */
    public function brand($param)
    {
        /*  品牌  */
        $brand = ProductBrand::where('is_del', 0)->field('id,name,image')->select();
        return Basic::data(0, 'common.success', $brand);
    }


    /**
     *  框架品牌
     */
    public function coin($param)
    {
        /*  品牌  */
        $ProductCurrency = ProductCurrency::where('is_del', 0)->where('if_show', 1)->field('id,name,algorithm')->select();
        return Basic::data(0, 'common.success', $ProductCurrency);
    }

    /**
     *  仓库
     */
    public function warehouse($param)
    {
        /*  品牌  */
        $Warehouse = Warehouse::where('is_del', 0)->field('id,show_name as name')->select();
        return Basic::data(0, 'common.success', $Warehouse);
    }

    /**
     *  筛选器分组
     */

    public function group($param)
    {
        $target = $param['lang'];
        // $brandData = $this->getBrandList($target);
        $cacheLogic = new CacheLogic();
        $brands = $cacheLogic->getAllBrands($target, $this->refresh, 'asc');

        foreach ($brands as $key => &$brand) {
            $brand['parent_key'] = 'brand';
            $brand['brand_logo'] = $brand['image'];
            $brand['label'] = $brand['name'];
            $brand['value'] = $brand['id'];
            unset($brand['image']);
            unset($brand['name']);
            unset($brand['translate_name']);
            unset($brand['description']);
            unset($brand['sort']);
        }

        // $coinData = $this->getCoinList($target);

        $coinData = $cacheLogic->getAllCoins($target, $this->refresh);

        foreach ($coinData as $key => &$coin) {

            $coin['parent_key'] = 'minable_coin';
            $coin['brand_logo'] = $coin['image'];
            $coin['label'] = $coin['name'];
            $coin['value'] = $coin['id'];
            $coin['num'] = $coin['num'];
            unset($coin['image']);
            unset($coin['name']);
            unset($coin['abbr']);
            unset($coin['sort']);
            unset($coin['translate_name']);
            unset($coin['algorithm']);
        }

        $warehouseData = $this->getWarehouseList($target);

        $data = [
            [
                'label' => 'Brand',
                'value' => 'brand',
                'children' => $brands
            ],
            [
                'label' => 'Minable Coin',
                'value' => 'minable_coin',
                'children' => $coinData
            ],
            [
                'label' => 'Warehouse',
                'value' => 'warehouse',
                'children' => $warehouseData
            ]
        ];

        return Basic::data(0, 'common.success', $data);
    }

    private function getBrandList($lang)
    {
        $brand =  Db::name('product_brand')
            ->alias('pb')
            ->join('product p', 'pb.id = p.brand')
            ->field('pb.id,pb.name,pb.image,count(pb.id) num')
            ->where([
                'pb.is_del' => 0,
                'p.status' => 1,
                'p.is_del' => 0
            ])
            ->order('num desc')
            ->group('pb.id')
            ->select();

        $brandList = [];
        foreach ($brand as $value) {
            $value['name'] = translateOne($value['name'], $lang);
            $brandList[] = [
                'parent_key' => 'brand',
                'brand_logo' => $value['image'],
                'label' => $value['name'],
                'value' => $value['id'],
                'num' => $value['num']
            ];
        }

        return $brandList;
    }
    private function getCoinList($lang)
    {
        $algorithmModel = new Algorithm();
        $algorithmList = (array)$algorithmModel->getAttributes('algorithm'); // 获取算法名称列表

        $algorithmPIds = [];  // 存储每个算法 ID 对应的去重产品 ID 集合

        $algorithmData = Db::table('db_product')
            ->where([
                ['is_del', '=', 0],
                ['status', '=', '1'] // 包含m.status条件
            ])
            ->whereNotNull('algorithm')
            ->field(['id,algorithm'])
            ->select()
            ->toArray();

        if (!$algorithmData) {
            return [];
        }
        foreach ($algorithmData as $item) {
            $algorithms = explode(',', $item['algorithm']);
            foreach ($algorithms as $algId) {
                if (isset($algorithmList[$algId])) {
                    // 使用算法ID作为键，存储产品 ID，确保去重
                    $algorithmPIds[$algId][$item['id']] = $item['id'];
                }
            }
        }

        // 统计每个算法 ID 对应的产品数量，并使用算法ID作为键
        $algorithmCounts = [];
        foreach ($algorithmPIds as $algId => $pmIds) {
            $algorithmCounts[$algId] = [
                'id' => $algId,
                'name' => $algorithmList[$algId],
                'num' => count($pmIds) // 统计去重后的产品数量
            ];
        }

        // 获取所有有产品的算法ID列表
        $algorithmsIds = array_column($algorithmCounts, 'id');

        // 获取币种列表
        $coinsList = Db::name('product_currency')
            ->field('id, name, image, algorithm, name_short as abbr')
            ->where('is_del', 0)
            ->where('if_show', 1)
            ->whereIn('algorithm', $algorithmsIds)
            ->order('sort asc')
            ->select()
            ->toArray();


        $minableCoinItems = [];

        foreach ($coinsList as $value) {
            $algIdForCoin = intval($value['algorithm']);
            $num =  in_array(intval($value['algorithm']), $algorithmsIds) ? $algorithmCounts[$algIdForCoin]['num'] : 0;
            if ($num > 0) {
                $value['name'] = translateOne($value['name'], $lang);
                $minableCoinItems[] = [
                    'parent_key' => 'minable_coin',
                    'label' => $value['name'],
                    'value' => $value['id'],
                    'image' => $value['image'],
                    'num' =>  $num
                ];
            }
        }

        return array_values($minableCoinItems);
    }

    private function getWarehouseList($lang)
    {
        $Warehouse = Warehouse::where('is_del', 0)->where('status', 1)->field('id,fl_warehouse_id,show_name as name')->order('id DESC')->select();

        $WarehouseItem = [];
        $parentItems = []; // 初始化父级项数组

        // 第一遍：处理所有父级项
        foreach ($Warehouse as $value) {
            if ($value->fl_warehouse_id === null) {
                if (isset($value->name) && $value->name) {
                    $tanslateParam[md5($value->name)] = $value->name;
                }
                $value->name = translateOne($value->name, $lang);

                $parentItems[$value->id] = [
                    'parent_key' => 'warehouse',
                    'label' => $value->name,
                    'value' => $value->id,
                    'children' => [] // 初始化子项
                ];
            }
        }

        // 第二遍：处理所有子级项
        foreach ($Warehouse as $value) {
            if ($value->fl_warehouse_id !== null) {
                if (isset($value->name) && $value->name) {
                    $tanslateParam[md5($value->name)] = $value->name;
                }
                $value->name = translateOne($value->name, $lang);

                $currentItem = [
                    'parent_key' => 'warehouse',
                    'label' => $value->name,
                    'value' => $value->id,
                    'children' => []
                ];

                // 添加到相应的父级项中
                if (isset($parentItems[$value->fl_warehouse_id])) {
                    $parentItems[$value->fl_warehouse_id]['children'][] = $currentItem;
                }
            }
        }
        // 将父级项转换为数组
        $WarehouseItem = array_values($parentItems);

        return $WarehouseItem;
    }
}
